class Grid < ActiveRecord::Base
  include ToHash

  has_many :items, :dependent => :destroy
  has_many :images, :dependent => :destroy
  has_many :links, :dependent => :destroy

  validates_presence_of :name, :rows, :columns
  validates_numericality_of :rows, :columns, :only_integer => true, :greater_than_or_equal_to => 1, :less_than_or_equal_to => 200
  validates_length_of :name, :maximum => 30

  def update_attributes(attributes)
    if attributes.has_key?(:items)
      attributes[:items] = attributes[:items].collect do |i|
        Item.new(i)
      end
    end
    super(attributes)
  end

  def to_json()
    to_hash(:id, :name, :description, :rows, :columns, [:items, :text, :location, :backgroundColor, :foregroundColor, :order],
    [:links, :from, :to]).to_json
  end

  def change_dimensions(rows, columns)
    if rows < self.rows || columns < self.columns
      Link.destroy_at_dimensions(rows, columns)
      Item.destroy_at_dimensions(rows, columns)
    end
    self.update_attributes!(:rows => rows, :columns => columns)
  end

end
